package com.yupi.yupao.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yupao.mapper.UserMapper;
import com.yupi.yupao.model.domain.User;
import com.yupi.yupao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author FengHuan Wang
 * @Date 2025/4/3 19:23
 * @Version 1.0
 */
@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private RedissonClient redissonClient;
    /**
     * 重点用户
     */
    private  List<Long> mainUserLiist = Collections.singletonList(1L);
    @Scheduled(cron = "0 56 23 * * *")
    public void doPreCacheRecommend() {
        RLock lock = redissonClient.getLock("yupao:precachejob:docache:lock");
        // 只有一个线程能获取到锁
        try {
            if ( lock.tryLock(0,30000, TimeUnit.MILLISECONDS)){
                for (Long userId : mainUserLiist) {
                    // 没有查到缓存，查询数据库
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> page = userService.page(new Page<>(1, 20), queryWrapper);
                    // 如果有缓存，直接插训redis缓存
                    String redisKey = String.format("yupao:user:recommend:%s", userId);
                    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
                    // 写缓存
                    try {
                        valueOperations.set(redisKey, page, 10000000, TimeUnit.MILLISECONDS);
                    } catch (Exception e) {
                        log.error("缓存写入时失败");
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("缓存异常，分布式锁");
        } finally {
            // 只能释放自己加的锁
            if (lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }




    }
}
